package org.snlab.util;


import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import com.fasterxml.jackson.core.exc.StreamReadException;
import com.fasterxml.jackson.databind.DatabindException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.snlab.compiler.DdmdConf;
import org.snlab.compiler.DdmdConfs;
import org.snlab.runtime.Config;
import org.snlab.runtime.Daemon;

public class Simnet {
    public static void main(String[] args) {
        Options options = new Options();
        options.addOption("e", true, "Env dir");
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd;
        
        try {
            cmd = parser.parse(options, args);
            DdmdConfs ddmdConfs = new DdmdConfs();
            ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
            ddmdConfs = objectMapper.readValue(new File(cmd.getOptionValue("e") + "/gen/ddmdconfs.yaml"), DdmdConfs.class);
            System.out.println("Using env " + cmd.getOptionValue("e"));
            Set<Thread> daemons = new HashSet<>();
            for (DdmdConf ddmdConf : ddmdConfs.getDdmdConfs()) {
                Config config = new Config();
                config.setName(ddmdConf.getName());
                config.setPort(ddmdConf.getPort());
                config.setFib(ddmdConf.getFib());
                config.setEnvDir(cmd.getOptionValue("e"));
                Daemon daemon = new Daemon(config);
                Thread thread = new Thread(daemon);
                thread.start();
                daemons.add(thread);
            }
            for (Thread thread : daemons) {
                thread.join();
            }
            System.out.println("eof");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

// def startDdmd(conf, nCpu):
//     cpu_str = ''
//     if nCpu != None:
//         cpu_str = '-XX:ActiveProcessorCount=%d' % nCpu
//     cmd = 'java ' + cpu_str + ' -jar ddmd.jar -n' + conf['name'] + ' -p ' + str(conf['port']) + ' -f ' + conf['fib']
//     # os.system(cmd)
//     subprocess.run([cmd], shell=True)

// def start(env_dir, nCpu):
//     with open(env_dir + '/ddmdconfs.yaml') as f:
//         parsed = yaml.safe_load(f)
//         threads = []
//         for ele in parsed['ddmdConfs']:
//             t = threading.Thread(target=startDdmd, args=(ele, nCpu,))
//             t.start()
//             threads.append(t)
//         for t in threads:
//             t.join()